package com.frkj.yuan.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.frkj.yuan.R;
import com.frkj.yuan.api.bean.AddJiuzhenPersonBean;
import com.frkj.yuan.api.bean.SelectServiceTimeBean;
import com.frkj.yuan.api.category.AddAutherBean;
import com.frkj.yuan.api.category.AddJiuzhenPersonCategory;
import com.frkj.yuan.api.presenter.AddJiuzhenPersonPresenter;
import com.frkj.yuan.base.BaseActivity;
import com.frkj.yuan.data.YuyueKeshiDataUtils;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.utils.FullScreenUtils;
import com.frkj.yuan.utils.IDCardValidateUtils;
import com.frkj.yuan.utils.SPUtils;
import com.frkj.yuan.utils.ToastUtil;
import com.msd.ocr.idcard.LibraryInitOCR;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：菲菲 on 2022/2/16 16:50
 * company：丰蓉信息科技有限公司
 */
public class AddJiuZhengPersonalActivity extends BaseActivity implements AddJiuzhenPersonCategory.View {
    @BindView(R.id.base_title)
    TextView mTitleMsg;
    @BindView(R.id.edit_name)
    EditText mEditName;
    @BindView(R.id.edit_idcard)
    EditText mEditCard;
    @BindView(R.id.edit_phone)
    EditText mEditPhone;
    private AddJiuzhenPersonPresenter mPresenter;
    private String mToken;
    @BindView(R.id.select_jiuzhen)
    TextView mSelectJiuZheng;
    private int mPersonalStates = 1;
    public static final int SCAN_IDCARD_REQUEST = 1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_jiuzheng;
    }

    @Override
    public void initLayoutView() {
        FullScreenUtils.getInstance().fullScreen(AddJiuZhengPersonalActivity.this, true);
        mTitleMsg.setText("添加就诊人");
        mPresenter = new AddJiuzhenPersonPresenter(this);
        SetPersenter(mPresenter);
        mToken = (String) SPUtils.get(AddJiuZhengPersonalActivity.this, ConstantStaticUrl.mToken, "");
    }

    @OnClick({R.id.base_back, R.id.submit_person, R.id.relat_nicheng, R.id.select_jiuzhen, R.id.scard_sfz})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finishWitchAnimation();
                break;
            case R.id.submit_person:
                String regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$";

                if (mEditName.getText().toString().trim().equals("")) {
                    ToastUtil.showToastINFO(AddJiuZhengPersonalActivity.this, "姓名不能为空");
                    mEditName.setText("");
                    return;
                } else if (mEditPhone.getText().toString().trim().equals("")) {
                    ToastUtil.showToastINFO(AddJiuZhengPersonalActivity.this, "手机号码不能为空");
                    mEditPhone.setText("");
                    return;
                } else if (!TextUtils.isEmpty(mEditPhone.getText().toString().trim()) && !mEditPhone.getText().toString().trim().matches(regExp)) {
                    ToastUtil.showToastINFO(AddJiuZhengPersonalActivity.this, "手机号码输入有误,请重新输入");
                    mEditPhone.setText("");
                    return;
                } else if (mEditCard.getText().toString().trim().equals("")) {
                    ToastUtil.showToastINFO(AddJiuZhengPersonalActivity.this, "请输入就诊人身份证号码");
                    return;
                } else {
                    try {
                        if (!IDCardValidateUtils.checkIdCardNum(mEditCard.getText().toString().trim())) {
                            ToastUtil.showToastINFO(AddJiuZhengPersonalActivity.this, "身份证号码输入有误");
                            mEditCard.setText("");
                        } else {
                            mPresenter.getAutherMsg(mToken, mEditCard.getText().toString());
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                break;
            case R.id.select_jiuzhen:
                BaseActivity.hideKeyBoard(this);
                SelectJiuZhengDialog();
                break;
            case R.id.scard_sfz:
                LibraryInitOCR.initOCR(this);
                Bundle sfenz = new Bundle();
                sfenz.putBoolean("saveImage", true);
                sfenz.putInt("requestCode", SCAN_IDCARD_REQUEST);
                sfenz.putInt("type", 0); //0身份证
                LibraryInitOCR.startScan(AddJiuZhengPersonalActivity.this, sfenz);
                break;
            case R.id.relat_nicheng:
                //判断是否有权限
                if (ContextCompat.checkSelfPermission(AddJiuZhengPersonalActivity.this, android.Manifest.permission.READ_CONTACTS)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(AddJiuZhengPersonalActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 201);
                } else {
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, 0);
                }
                break;
        }
    }

    private void SelectJiuZhengDialog() {
        List<String> listData = YuyueKeshiDataUtils.mSelectJiuZhengPersonal();
//      监听选中
        OptionsPickerView pvOptions = new OptionsPickerBuilder(AddJiuZhengPersonalActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//               返回的分别是三个级别的选中位置
//              展示选中数据
                mSelectJiuZheng.setText(listData.get(options1));
                if (listData.get(options1).equals("父母")) {
                    mPersonalStates = 1;
                } else if (listData.get(options1).equals("子女")) {
                    mPersonalStates = 2;
                } else if (listData.get(options1).equals("兄弟姐妹")) {
                    mPersonalStates = 3;
                } else if (listData.get(options1).equals("夫妻")) {
                    mPersonalStates = 4;
                } else if (listData.get(options1).equals("本人")) {
                    mPersonalStates = 5;
                } else if (listData.get(options1).equals("其他")) {
                    mPersonalStates = 6;
                }
            }
        })
                .setTitleText("请选择就诊人关系")
                .setCancelColor(Color.parseColor("#333333"))
                .setTextColorCenter(Color.parseColor("#ff512f")) //设置选中项文字颜色

                .setContentTextSize(18)
                .setSelectOptions(0)//设置选择第一个
                .setOutSideCancelable(false)//点击背的地方不消失
                .build();//创建
//      把数据绑定到控件上面
        pvOptions.setPicker(listData);
//      展示
        pvOptions.show();
    }
    @Override
    public void getAutherMsg(AddAutherBean auther) {
        if (auther.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (auther.getData() != null) {
                if (auther.getData().getCanInsert() == false) {
                    JSONObject result = new JSONObject();
                    try {
                        result.put("name", mEditName.getText().toString().trim());
                        result.put("contact", mEditPhone.getText().toString().trim());
                        result.put("cardNum", mEditCard.getText().toString().trim());
                        result.put("relation", mPersonalStates);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mPresenter.getAddjiuzhenPerson(mToken, result.toString());
                } else if (auther.getData().getCanInsert() == true) {
                    ToastUtil.showToastINFO(AddJiuZhengPersonalActivity.this, "相同身份证号就诊人已存在");
                }
            }
        } else {
            ToastUtil.showToastINFO(AddJiuZhengPersonalActivity.this, auther.getMsg());
        }
    }

    /**
     * @param baseInfor 添加就诊人信息
     */
    @Override
    public void getAddjiuzhenPerson(AddJiuzhenPersonBean baseInfor) {
        if (baseInfor.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            ToastUtil.showToastSUCCESS(AddJiuZhengPersonalActivity.this, "就诊人添加成功");
            openActivityWitchAnimation(JiuZhengPesonalActivity.class);
            finish();
        } else {
            ToastUtil.showToastERROR(AddJiuZhengPersonalActivity.this, baseInfor.getMsg());
        }
    }

    @Override
    public void getSelectTime(SelectServiceTimeBean serviceTimeBean) {

    }

    @Override
    public void SetPersenter(Object persenter) {
    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(AddJiuZhengPersonalActivity.this, mErrorMsg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                // TODO: 2022/4/12 此处设置处理通讯录返回信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
                mEditName.setText(contacts[0]);
                mEditPhone.setText(contacts[1]);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象**
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标**
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名**
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码**
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }
}
